<template>
  <div>
    <div class="room-table">
      <h2>未开出</h2>
      <el-table
        :data="canOpenRoomListData"
        border
        :key="Math.random()"
        style="width: 100%">
        <el-table-column
          prop="roomNum"
          label="房间号"
          align="center"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="roomType"
          label="类型"
          align="center"
          :formatter="typeFormat"
          :filters="roomTypeFilterConfig"
          :filter-method="filterType"
          width="180">
        </el-table-column>
        <el-table-column
          prop="roomPrice"
          label="价格"
          align="center"
          width="180">
        </el-table-column>
        <el-table-column
          label="状态"
          align="center">
          <span>待开出</span>
        </el-table-column>
        <el-table-column  
          label="操作"
          align="center">
          <template slot-scope="scope">
            <el-button size="mini" :disabled="scope.row.state==='1'" @click="openRoom(scope.row)">开房</el-button>
            <el-button size="mini" :disabled="true">退房</el-button>
            <el-button size="mini" :disabled="true">换房</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="开房" :visible.sync="outerVisible">
      <el-dialog
        width="30%"
        title="添加入住人员"
        :visible.sync="innerVisible"
        append-to-body>
        <el-autocomplete
          v-model="queryInfo"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入内容"
          @select="handleSelect"
        ></el-autocomplete>
      </el-dialog>
      <el-dialog
          width="30%"
          title="选择待分配订单"
          :visible.sync="innerVisibleOrder"
          append-to-body>
        <el-autocomplete
            v-model="queryInfoOrder"
            :fetch-suggestions="queryOrderSearchAsync"
            placeholder="请输入内容"
            @select="handleOrderSelect"
        ></el-autocomplete>
      </el-dialog>
      <h3>入住人员</h3>
      <el-table :data="userInfoList">
        <el-table-column property="userId" label="用户ID" width="150"></el-table-column>
        <el-table-column property="userName" label="姓名" width="150"></el-table-column>
        <el-table-column property="userGender" label="性别" :formatter="genderFormat" width="150"></el-table-column>
        <el-table-column property="userIdNumber" label="身份证" width="150"></el-table-column>
        <el-table-column property="userPhone" label="联系方式" width="150"></el-table-column>
      </el-table>
      <el-form :model="openRoomInfo" label-width="100px">
        <el-form-item label="房号">
          <el-input v-model="openRoomInfo.roomNum" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="开出时间">
          <el-date-picker
              type="datetime"
              placeholder="选择日期时间"
              v-model="openRoomInfo.date1"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="dateChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到期时间">
          <el-date-picker
              type="datetime"
              placeholder="选择日期时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="openRoomInfo.date2"
              @change="paymentChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="房费">
          <el-input v-model="openRoomInfo.totalPrice" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="绑定订单Id">
          <p>{{choiceOrderId}}</p>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="innerVisibleOrder = true">分配线上订单</el-button>
        <el-button @click="innerVisible = true" :disabled="choiceOrderId==''?false:true">添加入住人员</el-button>
        <el-button type="primary" @click="sendOpenRoom">确认开房</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'HomeRoomOpen',
  data(){
    return {
      // 未开房的房间信息
      canOpenRoomListData:[],
      // 开房配置
      openRoomInfo:{
        roomNum:'',
        date1:'',
        date2:'',
        roomPrice: 0,
        totalPrice: 0,
        userIdArr: []
      },
      // 新增的入住人员id
      addUserId:'',
      restaurants: [],
      queryInfo: '',
      timeout:  null,
      // 选择待分配订单
      orderRestaurants: [],
      queryInfoOrder: '',
      // 页面dialog配置
      outerVisible: false,
      innerVisible: false,
      innerVisibleOrder: false,
      // 页面用配置
      formLabelWidth: '120px',
      // 发送协议用的
      openRoomId:null,
      userArr:[],
      choiceOrderId: '',
    }
  },
  computed:{
    // 获取待开房状态的房间列表
    canOpenRoomList(){
      return this.$store.getters.getCanOpenRoomList || [];
    },
    // 获取房间类型名列表
    TypeNameList(){
      return this.$store.getters.getTypeNameList || {};
    },
    // 获取用户列表[{userName, userId}]
    userList(){
      return this.$store.getters.getUserList || [];
    },
    // 获取用户信息列表
    userInfoList(){
      return this.$store.getters.getUserInfoList || [];
    },
    // 获取筛选格式的类别列表[{text:...,value:...}]
    roomTypeFilterConfig(){
      return this.$store.getters.getTypeFilterConfig || [];
    },
    // 获取线上待分配订单id列表
    getOnlineOrderListLocalInfo(){
      return this.$store.getters.getOnlineOrderListLocalInfo || [];
    },
    // 根据choiceOrderId获取订单信息
    getChoiceOrderInfo(){
      return this.$store.getters.getOrderInfoByOrderIdOne || [];
    }
  },
  mounted() {
    this.$store.dispatch('getUserList');
    this.$store.dispatch('getOnlineOrder');
    setTimeout(()=>{
      this.restaurants = this.userList;
      this.orderRestaurants = this.getOnlineOrderListLocalInfo;
    }, 1000)
  },
  methods:{
    openRoom(room){
      console.log(room)
      this.openRoomId=room.roomId;
      this.openRoomInfo.roomNum=room.roomNum;
      this.openRoomInfo.roomPrice=room.roomPrice;
      this.openRoomInfo.date1='';
      this.openRoomInfo.date2='';
      this.openRoomInfo.userIdArr = [];
      this.openRoomInfo.totalPrice=room.roomPrice;
      this.$store.dispatch('getUserInfoList', {userIdArr:this.openRoomInfo.userIdArr.toString()});
      this.outerVisible=true;
    },
    sendOpenRoom(){
      let openConfig = {};
      const now = Date.now();
      //使用全局事件间时间戳转为dateTime格式
      this.$bus.$emit('timeTrans', now, (date)=>{
        openConfig['createTime'] = date;
      })
      openConfig['roomId'] = this.openRoomId;
      openConfig['openInfo'] = this.openRoomInfo;
      openConfig['choiceOrderId'] = this.choiceOrderId;
      // 发请求协议
      this.$store.dispatch('openRoom', openConfig);
      setTimeout(()=>{
        this.$store.dispatch('getRoomListData');
        this.$store.dispatch('getOnlineOrder');
      }, 500);
      this.outerVisible = false;
    },
    dateChange(){   //设置到期默认时间
      let day=new Date(new Date().getTime()+24*60*60*1000);
      let month=day.getMonth()+1;
      let date=day.getDate();
      month=month<10?'0'+Number(month):month;   //小于10情况
      date=date<10?'0'+date:date;

      this.openRoomInfo.date2=`${day.getFullYear()}-${month}-${date} 12:00:00`;
      this.paymentChange();
    },
    paymentChange(){   //根据开房时间和到期时间的天差来动态计算需要的支付的费用
      let date1=new Date(this.openRoomInfo.date1);
      let date2=new Date(this.openRoomInfo.date2);
      let date3=date2.getTime()-date1.getTime();
      let days=Math.ceil(date3/(24*3600*1000));   //向上取整，超过1天算2天
      this.openRoomInfo.totalPrice=days*this.openRoomInfo.roomPrice;
    },
    // 将类型号转换为类型显示
    typeFormat(row, column, cellValue){
      if (cellValue == null || cellValue == '') return '';
      const typeNameList = this.TypeNameList;
      return typeNameList[parseInt(cellValue)];
    },
    // 添加入住人员dialog
    querySearchAsync(queryString, cb) {
      let restaurants = this.restaurants;
      let results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 800 * Math.random());
    },
    createStateFilter(queryString) {
      return (queryInfo) => {
        return (queryInfo.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      if (this.openRoomInfo.userIdArr.indexOf(item.userId)=='-1'){
        this.openRoomInfo.userIdArr.push(item.userId);
        this.$message({
          showClose:true,
          message:'入住人员添加成功！',
          type:"success"
        })
        this.$store.dispatch('getUserInfoList', {userIdArr:this.openRoomInfo.userIdArr.toString()});
      }else{
        this.$message({
          showClose:true,
          message:'入住人员已存在，添加失败！',
          type:"error"
        })
      }
      this.innerVisible = false;
      this.queryInfo = '';
    },
    // 性别转换0->男，1->女
    genderFormat(row, column, cellValue){
      if (cellValue == null || cellValue == '') return '';
      const genderConfig = ['男', '女'];
      return genderConfig[parseInt(cellValue)];
    },
    // 类别筛选功能配置
    filterType(value, row, column) {
      return row.roomType === value;
    },
    // 选择待分配房间dialog
    queryOrderSearchAsync(queryString, cb) {
      let orderRestaurants = this.orderRestaurants;
      let results = queryString ? orderRestaurants.filter(this.createOrderStateFilter(queryString)) : orderRestaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 800 * Math.random());
    },
    createOrderStateFilter(queryString) {
      return (queryInfo) => {
        return (queryInfo.value.toString().toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleOrderSelect(item) {
      if (this.choiceOrderId != item.value.toString()){
        this.choiceOrderId = item.value.toString();
        this.$message({
          showClose:true,
          message:'选择订单成功！',
          type:"success"
        })
        this.$store.dispatch('getOrderInfo', {send:{orderId:this.choiceOrderId},type:1});
        setTimeout(()=>{
          this.$store.dispatch('getUserInfoList', {userIdArr:this.getChoiceOrderInfo[0].userIdArr.toString()});
        }, 500)
      }else{
        this.$message({
          showClose:true,
          message:'该订单已被选择，重复选择失败！',
          type:"error"
        })
      }
      this.innerVisibleOrder = false;
      this.queryOrderInfo = '';
    },
  },
  watch:{
    userList(){
      this.restaurants = this.userList;
    },
    getOnlineOrderListLocalInfo(){
      this.orderRestaurants = this.getOnlineOrderListLocalInfo;
    },
    canOpenRoomList:{
      handler(){
        this.canOpenRoomListData = this.canOpenRoomList;
      },
      deep:true
    }
  }
}
</script>

<style scoped>

</style>

